package com.hoppinzq.service.hander;

import com.alibaba.fastjson.JSONObject;
import com.hoppinzq.service.annotation.GatewayServlet;
import com.hoppinzq.service.bean.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


/**
 * 网关参数处理
 * 通过继承本类，自定义网关的默认行为，如重写afterSuccessRequest方法以在网关成功响应前做一些你自己的事情。
 * 通过RequestContext类，获取该线程本次请求所有信息。使用这些信息，你可以在自定义重写方法做一些事情，如获取用户信息进行鉴权等。
 * @author:ZhangQi
 */
@GatewayServlet(prefix = "/service/hoppinzq",description = "这是自带的网关")
public class ApiGatewayDefaultHandler extends AbstractApiGatewayHandler{
    private static final Logger logger = LoggerFactory.getLogger(ApiGatewayDefaultHandler.class);

    @Autowired
    private ApiPropertyBean apiPropertyBean;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        super.handle(request, response);
    }

    /**
     * 网关统一返回值封装返回值（重写）
     * @param request
     * @param response
     * @param result
     * @throws IOException
     */
    @Override
    public void setOutParam(HttpServletRequest request, HttpServletResponse response, Object result,RequestParam requestParam) throws IOException {
        PrintWriter out = response.getWriter();
        if(requestParam.getApiRunnable()==null){
            out.println(result.toString());
        }else{
            ServiceMethodApiBean serviceMethodApiBean=requestParam.getApiRunnable().getServiceMethodApiBean();
            if(serviceMethodApiBean.methodReturn){
                out.println(result.toString());
            }else{
                JSONObject resultJson=JSONObject.parseObject(result.toString());
                //配置不封装返回值的情况：若报错，依然使用封装的返回值
                if(resultJson.get("data")==null){
                    out.println(resultJson);
                }else{
                    out.println(resultJson.get("data").toString());
                }

            }
        }
    }

}
